Ext.Loader.setPath('Ext.ux.LayuiIconPicker', contextPath+'pickers/LayuiIconPicker.js');
Ext.Loader.setPath('Ext.ux.FaIconPicker', contextPath+'pickers/FaIconPicker.js');
Ext.Loader.setPath('FormFieldUtil', contextPath+'ui_tpl/FormFieldUtil.js');
;(function(Ext,metaData){
	var pickerMap={"layui_icon_picker":"Ext.ux.LayuiIconPicker","fa_icon_picker":"Ext.ux.FaIconPicker"},
	mainMetaId=metaData["id"],
	mainMeta=refMetaMap[mainMetaId],
	fields=mainMeta["fields"],
	attrs=mainMeta["attrs"],
	fields=mainMeta["fields"],
	requires=[
		'Ext.tree.TreePanel',
		'Ext.form.Panel',
		'Ext.data.TreeStore',
		'FormFieldUtil'
	];
	var action=attrs["action"]||{url:contextPath+"meta/record/"+metaData["id"],type:"rest"};
	var update=attrs["update"]||action;
	update["url"]=update["url"]||action["url"];
	update["type"]=update['type']||action["type"];
	
	Ext.iterate(fields,function(field,i){
		var attrs=field["attrs"],picker=attrs["picker"];
		if(picker){
			requires.push(pickerMap[picker]);
		}
	});
	Ext.define("Ext.ux.TreeForm",{
		requires:requires,
		extend:'Ext.container.Container',
		xtype:'treeform',
		layout:'border',
		initComponent:function(){
			var me=this;
			this.mainMetaId=mainMetaId;
			this.treeCmpId="treeCmpId";
			this.metaData=metaData;
			this.attrs=mainMeta["attrs"];
			this.idProperty=this.attrs["idProperty"]||"id";
			this.parentIdProperty=this.attrs["parentIdProperty"]||"fid";
			var move=this.attrs["move"]||{url:"/meta/moveseq"};
			this.moveSeqUrl=move["url"];
			me.initTree('west');
			me.initDetailForm('center');
			this.items=[me.treeConfig,me.detailFormConfig];
			this.callParent();
		},
		initTreeTBar:function(){
			var me=this,
			
			tbar=[{
				text:"新增",
				iconCls:"fa fa-plus-circle fa-fw",
				handler:function(){
					me.showAddNodeWin();
				}
			},{
				text:"删除",
				iconCls:"fa fa-trash-o fa-fw",
				handler:function(){
					me.doDelete();
				}
			},{
				text:"刷新",
				iconCls:"fa fa-refresh fa-fw",
				handler:function(){
					this.up('treepanel').store.reload();
				}
			}];
			return tbar;
			
		},
		initTreeBbar:function(){
			
		},
		refreshSelectedNode:function(){
			var me=this,tree=Ext.getCmp(me.treeCmpId),sels=tree.getSelection(),
			store=tree.store;
			if(sels.length==0){
				return store.reload();
			}
			var sel=sels[0],id=sel.get("id");
			me.refreshNode(id);
		},
		refreshNode:function(id){
			var me=this,tree=Ext.getCmp(me["treeCmpId"]),
	    	store=tree.store;
	    	var node = store.getNodeById(id),fid=node.raw.fid,
	    	fidNode=store.getNodeById(fid);
	    	store.load({node: fidNode, callback:function() {
	           var fidNode = store.getNodeById(fid);
	            tree.getSelectionModel().select(node, true, true);
	            fidNode.expand();
	        }, scope: this});
		},
		
		reloadNode:function(id){
			var me=this,tree=Ext.getCmp(me["treeCmpId"]),
	    	store=tree.store;
	    	var node = store.getNodeById(id);
	    	store.load({node: node, callback:function() {
	           var currentNode = store.getNodeById(node.raw.id);
	            tree.getSelectionModel().select(node, true, true);
	            node.expand();
	        }, scope: this});
		},
		
		buildTreeModel:function(){
			return new Ext.data.TreeModel({
				 clientIdProperty: 'clientId',
				 identifier: 'negative',
				idProperty:"id"
			});
			
		},
		initTreeStore:function(){
			var me=this,attrs=me["attrs"],
			treeModel=this.buildTreeModel(),
			query=attrs["action"]||{type:"rest",url:""},
			queryUrl=query["url"];

			var proxy=this.buildProxy();
			
			var store= {
				autoDestroy :true,
				autoLoad :true,
				autoSync:true,
				proxy:proxy,
				defaultRootId:attrs["rootId"],
				defaultRootText:attrs["rootText"]||mainMeta["text"],
				parentIdProperty:me.parentIdProperty,
				model:treeModel,
				nodeParam:me.idProperty
			};
			return store;
		},
		initTree:function(region){
			var me=this,store=this.initTreeStore(),treeCmpId=this.treeCmpId,
			tbar=this.initTreeTBar();
			var treeConfig=this.treeConfig={
					xtype: 'treepanel',
					rootVisible:true,
					store:store,
					id:treeCmpId,
					split:true,
					viewConfig: {
				        plugins: {
				            ptype: 'treeviewdragdrop',
				            containerScroll: true
				        },
				        enableTextSelection:true
				    },
					autoLoad:true,
					region:region,
					height:400,
					width:300,
					tbar:tbar,
					listeners:{
						'itemclick':function ( view, record, item, index, e, eOpts ) {
							var cmp=Ext.getCmp(me["detailFormId"]);
							Ext.apply(record.data,Ext.Object.flatten(record.data));
							cmp.loadRecord(record);
						},
						'itemmove':function( node, oldParent, newParent, index, eOpts )  {
							var params={id:node.raw.id,fid:newParent.raw.id,seq:index};
							Ext.Ajax.request({
								url:me.moveSeqUrl,
								params:params,
								success:function(response, opts) {
									me.reloadNode(oldParent.raw.id);
									if(oldParent!=newParent){
										me.reloadNode(newParent.raw.id);
									}
									
							     },
								failure:function(response, opts){
									me.reloadNode(oldParent.raw.id);
									if(oldParent!=newParent){
										me.refreshSelectedNode();
									}
								}
							});
						}
						
					}
			};
			return treeConfig;
		},
		initDetailForm:function(region){
			var me=this,attrs=me["attrs"];
			me["detailFormId"]="detailForm"+me["metaData"]["id"]
			,items=FormFieldUtil.getFormFields(me["mainMetaId"],metaData);
			var config=this.detailFormConfig={
					xtype:'form',
			    title: '详细信息',
			    bodyPadding: 15,
			    region:region,
			    width: 350,
			    scrollable:true,
			    layout: 'anchor',
			    defaults: {
			        anchor: '100%',
			        labelAlign:'right'
			    },
			    id:me["detailFormId"],
			    defaultType: 'textfield',
			    items:items,
			    buttons: [{
			        text: '重置',
			        iconCls:"fa fa-refresh fa-fw",
			        handler: function() {
			            this.up('form').getForm().reset();
			        }
			    }, {
			        text: '提交',
			        iconCls:"fa fa-arrow-up",
			        formBind: true,
			        disabled: true,
			        handler: function() {
			            var form = this.up('form').getForm();
			            if (form.isValid()) {
			                form.submit({
			                    success: function(form, action) {
			                    	Ext.toast("提交成功",'提示', 't');
			                    	me.refreshSelectedNode();
			                    	
			                    },
			                    failure: function(form, action) {
			                    	Ext.toast(action.result.message,'提示', 't');
			                    	me.refreshSelectedNode();
			                    }
			                });
			            }
			        }
			    }]
			};
			if(update["type"]=="json"){
				config["jsonSubmit"]=true;
			}
			config["url"]=update["url"];
			return config;
		},
		
		showAddNodeWin:function(){
			var me=this,moduleId=me["mainMetaId"],attrs=me["attrs"],
			idProperty=attrs["idProperty"]||"id",
			typeProperty=attrs["typeProperty"]||"meta",
			winName=this.addNodeWinName="addNodeWin"+moduleId,
			action=attrs["action"];
			var win=Ext.getCmp(winName);
			if(!win){
				var items=FormFieldUtil.getFormFields(moduleId,metaData);
				Ext.iterate(items,function(item,i){
					var name=item["name"];
					if(name=="rank"){
						item.value=(moduleId);
						item.hidden=true;
					}else if(name==idProperty){
						item.value=-1;
						item.hidden=true;
					}else if(name=="seq"){
						item.hidden=true;
					}else if(name=="flag"){
						item.value=1;
					}else if(name==typeProperty){
						
					}
				});
				win=new Ext.form.Panel({
					floating:true,
					title:"新增",
					bodyPadding:10,
					url:action["url"],
					closeToolText:"关闭",
					draggable:true,
					closable:true,
					scrollable:true,
					width:400,
					height:400,
					defaults:{
						xtype:"textfield",
						width:300
					},
					method:action["method"]||"PUT",
					items:items,
					buttons:[{
						text:'提交',
						formBind:true,
						handler:function(){
							 var win=this.up('form'),form = win.getForm();
					            if (form.isValid()) {
					                form.submit({
					                    success: function(form, action) {
					                    	Ext.toast(action.result.msg,'提示', 't');
					                    	me.refreshSelectedNode();
					                    	win.hide();
					                    	
					                    },
					                    failure: function(form, action) {
					                    	Ext.toast(action.result.message,'提示', 't');
					                    	me.refreshSelectedNode();
					                    	win.hide();
					                    }
					                });
					            }	
						}
					},{
						text:'取消',
						handler:function(){
							this.up('form').hide();
						}
					}]
				});
			}
			var sels=Ext.getCmp(me.treeCmpId).getSelection();
			if(sels.length==0)return Ext.toast('请先选择父节点');
			win.getForm().findField(me.parentIdProperty).setValue(sels[0].get(me.idProperty));
			win.show();
			
		},
		buildProxy:function(){
			var attrs=this["attrs"],create=attrs["create"]||action,
			api={},actionMethods={},proxy={};
			if(action&&action.type=="rest"){
				proxy["type"]="rest";
				proxy["url"]=action["url"];
				proxy["appendId"]=true;
			}else{
				proxy["type"]="ajax";
				api["create"]=create.url;
				actionMethods["create"]=create.method||"POST";
				api["query"]=query.url;
				actionMethods["query"]=query.method||"GET";
				api["destroy"]=destroy.url;
				actionMethods["destroy"]=destroy.method||"GET";
				api["update"]=update["url"];
				actionMethods["update"]=update["method"]||"POST";
				proxy["url"]=query.url;
				proxy["type"]="ajax";
				proxy["api"]=api;
				proxy["appendId"]=true;
				proxy["actionMethods"]=actionMethods;
			}
			
			proxy["reader"]={
				type:action["format"]||"json",
				rootProperty:'children',
				typeProperty:this.metaData["typeProperty"]||"meta"
			};
			return proxy;
		},
		
		doDelete:function(){
			var me=this,tree=Ext.getCmp(me.treeCmpId),sels=tree.getSelection(),store=tree.store;
			
			if(sels.length==0)return Ext.toast('请先选择要删除的项目');
			var sel=sels[0],id=sel.get("id"),node=store.getNodeById(id);
			
			Ext.Msg.confirm('警告','确定要删除吗?',function(btn){
				if(btn=="no")return;
				node.erase();  
			});
		},
		getAddDefaultFields:function(){
			
		}
		
	});

	Ext.application({
	    name: 'MyApp',
	    mainView:'Ext.ux.TreeForm',
	    launch: function () {
	    }
	});
})(Ext,metaData);




